<?php
/**
 * Created by 无所谓已
 * User: Administrator
 * Date: 2025-08-26
 * Time: 0:16
 */

namespace plugin\csauto\app\service;

use plugin\csauto\app\model\SystemModel;
use Shopwwi\LaravelCache\Cache;
use support\Db;
use function Symfony\Component\Clock\now;


class SystemService
{
    const TASK_SEED_RETENTION_TIME = 'task_seed_retention_time '; /*任务最大做种时间-小时*/
    const TASK_SEED_DOWNLOAD_TIME = 'task_seed_download_time '; /*任务最大下载时间-小时*/
    const TASK_SEED_SURVIVE_TIME = 'task_seed_survive_time';/*任务最大存活时间-小时*/

    const TASK_RSS_MAX_SPACE = 'task_rss_max_space';/*种子最大大小-GB*/
    const TASK_RSS_MIN_SPACE = 'task_rss_min_space';/*种子最小大小-GB*/
    const TASK_SKIP_CHECKING = 'task_skip_checking';/*任务是否跳过检查 0 false 1 true*/
    const TASK_SUPER_SEEDING = 'task_super_seeding';/*超级做种模式*/
    const TORRENT_VIEW_IMG_MIN_NUM = 'torrent_view_img_min_num';
    const BAN_PICTURE_BED = 'ban_picture_bed';/*图床黑名单*/
    const MEDIAINFO_RETRY_MAX_COUNT = 'mediainfo_retry_max_count';/*MediaInfo获取最大重试次数*/

    const NC_THROTTLED_TASK_LIMIT = 'nc_throttled_task_limit';/*NC服务器限速时的最大任务数*/

    const RELEASE_RETRY_MAX_COUNT = 'release_retry_max_count';/*发布失败最大重试次数*/
    const ENABLE_RELEASE_DEBUG_LOG = 'enable_release_debug_log';/*启用发布任务调试日志*/
    
    const ACTIVE_TASK_SIZE_THRESHOLD = 'active_task_size_threshold';/*活跃任务大小阈值(MB)*/
    const ACTIVE_TASK_COUNT_LIMIT = 'active_task_count_limit';/*活跃任务数量限制*/
    const SYSTEM_VERSION = 'system_version';/*系统版本号*/

    const USER_ID = 'user_id';/*用户ID*/
    const USER_TOOL_KEY = 'user_tool_key';/*用户的tool Key*/
    const USER_TOOL_TOKEN = 'user_tool_token';/*工具的Token*/
    const IYUU_TOKEN = 'iyuu_token';/*IYUU令牌*/

    public static $systemConfig = [
//        self::MAX_DOWNLOAD_COUNT => 5,
        self::TASK_SEED_RETENTION_TIME => [
            'name' => '任务最大做种时间(小时)',
            'value' => 6,
            'note' => '任务最大做种时间(按照最后一个发布种的时间计算),即使没有完成出种要求也会被删除'
        ],
        self::TASK_SEED_DOWNLOAD_TIME => [
            'name' => '任务最大下载时间(小时)',
            'value' => 6,
            'note' => '任务最大下载时间，如未完成源站种下载会触发任务删除机制'
        ],
        self::TASK_SEED_SURVIVE_TIME => [
            'name' => '任务最大存活时间(小时)',
            'value' => 72,
            'note' => '任务最大存活时间(按照任务添加时间)，达到时间任务将会被无条件删除不论他是否完成下载或者完成发布'
        ],
//        self::TASK_DOWNLOAD_MAX_SPACE => 200,
        self::TASK_RSS_MAX_SPACE => [
            'name' => "RSS种子最大体积(GB)",
            'value' => 40,
            'note' => 'RSS任务中允许的最大种子体积,超出将不会纳入任务队列'
        ],
        self::TASK_RSS_MIN_SPACE => [
            'name' => "RSS种子最小体积(GB)",
            'value' => 0,
            'note' => 'RSS任务中允许的最小种子体积,小于将不会纳入任务队列'
        ],
        self::TASK_SKIP_CHECKING => [
            'name' => "任务发布是否跳过检查",
            'value' => 1,
            'note' => '1 为 跳过检查  0 为不跳过检查'
        ],
        self::TORRENT_VIEW_IMG_MIN_NUM => [
            'name' => "任务详情最小图片数量",
            'value' => 3,
            'note' => '默认为3 如果检测未达到详情图片数量会触发自动截图补全'
        ],
        self::BAN_PICTURE_BED => [
            'name' => "图床黑名单",
            'value' => 'rains3.com,img.m-team.cc,totheglory.im/details,i.miji.bid,duan.red',
            'note' => '图床黑名单域名列表，多个域名用英文逗号分隔，黑名单内的图片不计入详情图片数量统计',
            'readonly' => true
        ],
        self::MEDIAINFO_RETRY_MAX_COUNT => [
            'name' => "MediaInfo获取最大重试次数",
            'value' => 10,
            'note' => 'MediaInfo获取失败时的最大重试次数，达到次数后任务将终止'
        ],
        self::NC_THROTTLED_TASK_LIMIT => [
            'name' => "NC服务器限速时的最大任务数",
            'value' => 2,
            'note' => '当检测到NC服务器被限速时，每个下载器的最大任务数限制'
        ],
        self::RELEASE_RETRY_MAX_COUNT => [
            'name' => "发布失败最大重试次数",
            'value' => 10,
            'note' => '发布任务失败时的最大重试次数，达到次数后任务将终止，不再继续重试'
        ],
        self::ENABLE_RELEASE_DEBUG_LOG => [
            'name' => "启用发布任务调试日志",
            'value' => 0,
            'note' => '启用后将输出详细的发布任务调试日志（包含tag、简介等数据流转信息），用于排查发布问题。0=关闭，1=启用'
        ],
        self::IYUU_TOKEN => [
            'name' => "IYUU令牌",
            'value' => '',
            'note' => 'IYUU通知服务的令牌，用于发送通知到IYUU'
        ],
        self::ACTIVE_TASK_SIZE_THRESHOLD => [
            'name' => "活跃任务大小阈值(MB)",
            'value' => 2,
            'note' => '判断大于多少MB的下载速度属于活跃任务，默认2MB'
        ],
        self::ACTIVE_TASK_COUNT_LIMIT => [
            'name' => "活跃任务数量限制",
            'value' => 10,
            'note' => '当活跃任务数量大于此值时，下载器暂不分配新任务，默认10个'
        ],
        self::SYSTEM_VERSION => [
            'name' => "系统版本号",
            'value' => '1.2.0.1762271678', // 2025-07-05 时间戳，每次迭代更新此值 - 添加FFmpeg字幕滤镜截图支持
            'note' => '当前系统版本号（不可编辑）',
            'readonly' => true
        ],
//        self::TASK_SUPER_SEEDING => 1
    ];
    public static $systemDelete = [];

    public static function updateSystemDb()
    {
        addlog('updateSystemDb', 'update', 'info');
        foreach (self::$systemConfig as $key => $item) {
            $systemData = SystemModel::query()->where('key', $key)->first();
            if ($systemData) {
                /*更新名称和备注*/
                $systemData->name = $item['name'];
                $systemData->note = $item['note'];
                
                // 如果是版本号配置，需要更新value以跟随代码迭代
                if ($key === self::SYSTEM_VERSION) {
                    $systemData->value = $item['value'];
                }
                
                if (isset($item['readonly'])) {
                    $systemData->readonly = $item['readonly'] ? 1 : 0;
                }
                $systemData->updated_at = now();
                $systemData->save();
            } else {
                $insertData = array(
                    'key' => $key,
                    'name' => $item['name'],
                    'value' => $item['value'],
                    'note' => $item['note'],
                    'created_at' => now(),
                    'updated_at' => now()
                );
                if (isset($item['readonly'])) {
                    $insertData['readonly'] = $item['readonly'] ? 1 : 0;
                }
                SystemModel::query()->insert($insertData);
            }
            /*每次初始化清理缓存*/
            Cache::store('file')->delete(self::getCacheKey($key));
        }
        /*开始处理删除进程*/
        foreach (self::$systemDelete as $itemKey) {
            SystemModel::query()->where('key', $itemKey)->delete();
        }
    }

    public static function getCacheKey($key)
    {
        return "config::{$key}";
    }

    public static function getConfig($key)
    {
        $cacheData = Cache::store('file')->get(self::getCacheKey($key));
        if (empty($cacheData)) {
            $systemData = SystemModel::query()->where('key', $key)->first();
            if ($systemData) {
                Cache::store('file')->put(self::getCacheKey($key), $systemData->value);
                return $systemData->value;
            }
            return isset(static::$systemConfig[$key]) ? static::$systemConfig[$key] : null;
        }
        return $cacheData;
    }

    /**
     * 发送IYUU通知
     * @param string $title 通知标题
     * @param string $content 通知内容
     * @return bool 是否发送成功
     */
    public static function sendIyuNotification($title, $content)
    {
        $token = self::getConfig(self::IYUU_TOKEN);

        if (empty($token)) {
            addlog('IYUU令牌未配置，无法发送通知', 'IYUU', 'warning');
            return false;
        }

        $url = "https://iyuu.cn/{$token}.send";

        try {
            $postData = [
                'text' => $title,
                'desp' => $content
            ];

            // 使用file_get_contents发送POST请求
            $context = stream_context_create([
                'http' => [
                    'method' => 'POST',
                    'header' => 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
                    'content' => http_build_query($postData),
                    'timeout' => 30
                ]
            ]);

            $result = file_get_contents($url, false, $context);

            if ($result === false) {
                addlog('IYUU通知发送失败：请求超时或网络错误', 'IYUU', 'error');
                return false;
            }

            $response = json_decode($result, true);

            if ($response && isset($response['errcode']) && $response['errcode'] === 0) {
                addlog('IYUU通知发送成功：' . $title, 'IYUU', 'info');
                return true;
            } else {
                $errorMsg = isset($response['errmsg']) ? $response['errmsg'] : '未知错误';
                addlog('IYUU通知发送失败：' . $errorMsg, 'IYUU', 'error');
                return false;
            }

        } catch (\Exception $e) {
            addlog('IYUU通知发送异常：' . $e->getMessage(), 'IYUU', 'error');
            return false;
        }
    }
}